package 数组;

import java.util.Arrays;

/**
 * 移动零
 * 给定一个数组 nums，编写一个函数将所有 0 移动到数组的末尾，同时保持非零元素的相对顺序。
 * 输入: [0,1,0,3,12]
 * 输出: [1,3,12,0,0]
 * <p>
 * 1、
 * <p/>
 * User: zhaixiaolong Date:2024/1/26 9:27 ProjectName: algorithm Version:
 */
public class 移动零 {


    public static void main(String[] args) {

        int[] nums = {0,1,0,3,12};
        removeZero(nums);
        System.out.println(Arrays.toString(nums));

    }

    /**
     * 输入: [0,1,0,3,12]
     * 输出: [1,3,12,0,0]
     *
     * @param nums
     */
    public static void removeZero(int[] nums) {
        // 删除0
        int endIndex = delZero(nums,0);
        // 后置0
        for (;endIndex< nums.length;endIndex++){
            nums[endIndex] = 0;
        }
    }

    /**
     * 10034
     * @param nums
     * @param target
     * @return
     */
    public static int delZero(int[] nums, int target) {
        int slowIndex = 0;
        for (int fastIndex = 0; fastIndex < nums.length; fastIndex++) {
            if (nums[fastIndex] != target){
                nums[slowIndex] = nums[fastIndex];
                slowIndex ++;
            }
        }
        return slowIndex;
    }
}
